#!/bin/bash
[[ $(id -u) != 0 ]] && echo -e "请使用root权限运行安装脚本" && exit 1

cmd="apt-get"

install() {
	echo "================欢迎使用云矿！================"


    $cmd update -y
    $cmd install curl wget screen -y
	killall screen
	killall neihe
	rm -rf /root/yunkuang3
    mkdir /root/yunkuang3

    if ! [ -x "$(command -v git)" ]; then
    	echo "未发现git，正在安装，请稍后..."
    	$PM update
    	$PM install git -y
    fi
    git clone https://e.coding.net/suminer/suminer/yunkuang3.0.git /root/yunkuang3
    chmod -R 777 /root/yunkuang3
	cp /root/yunkuang3/tool.sh /bin/yunkuang
	/root/yunkuang3/install.sh
    echo "如果没有报错则安装成功"
    echo "正在启动..."
	screen -dmS yunkuang3 
	sleep 0.2s
    screen -r yunkuang3 -p 0 -X stuff "cd /root/yunkuang3"
    screen -r yunkuang3 -p 0 -X stuff $'\n'
	screen -r yunkuang3 -p 0 -X stuff "./client"   
    screen -r yunkuang3 -p 0 -X stuff $'\n'
    sleep 1s
	myFile="/etc/rc.local"
	if [ ! -f "$myFile" ]; then
		touch "$myFile"
		chmod 777 /etc/rc.local
		echo "#!/bin/bash" >> /etc/rc.local
		echo "exit 0" >> /etc/rc.local
	fi
	echo /dev/null > /etc/rc.local
	sed -i '1d' /etc/rc.local
	echo "#!/bin/bash" >> /etc/rc.local
    echo "screen -dmS yunkuang3" >> /etc/rc.local
	echo "sleep 0.2s" >> /etc/rc.local
	echo "screen -r yunkuang3 -p 0 -X stuff \"cd /root/yunkuang3\"" >> /etc/rc.local
	echo "screen -r yunkuang3 -p 0 -X stuff $'\n'" >> /etc/rc.local
    echo "screen -r yunkuang3 -p 0 -X stuff \"./client\"" >> /etc/rc.local  
	echo "screen -r yunkuang3 -p 0 -X stuff $'\n'" >> /etc/rc.local
	echo "exit 0" >> /etc/rc.local
    echo "yunkuang开机自启动已生效"
	myip=$(echo $(ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"))
    echo -e "\033[41;37m 如果您跟矿机在同一局域网下，请在浏览器打开以下网址启动后台\r\n $myip:8080 \033[0m"
	echo "\033[41;37m <<<如果您跟矿机不在在同一局域网下，请在点击下面链接登录后根据视频操作启动后台 \033[0m"
	tailscale up
	echo "云矿全体工作人员感谢您的安装和使用！"

    
}

remove() {


    killall yunkuang
	killall screen 
	apt-get remove tailscale
	echo "卸载完成，感谢您的使用！"

    
}


echo "======================================================="
echo "yunkuang 一键工具 V3.0.0"
echo "  1、安装"
echo "  2、卸载"


echo "======================================================="
read -p "$(echo -e "请选择[1-9]：")" choose
case $choose in
1)
    install
    ;;
2)
    remove
    ;;
*)
    echo "输入错误请重新输入！"
    ;;
esac
